package com.zx.eval.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zx.common.utils.HttpGetUtil;
import com.zx.common.utils.PageUtils;
import com.zx.common.utils.Query;
import com.zx.common.utils.SnowflakeIdWorker;
import com.zx.eval.dao.MemberDao;
import com.zx.eval.entity.MemberEntity;
import com.zx.eval.service.MemberService;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.codehaus.xfire.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    private Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
                .orderByDesc("create_time")
        );

        return new PageUtils(page);
    }

    @Override
    public MemberEntity memberLogin(Map<String, Object> temp) {
        MemberEntity member = new MemberEntity();
        try {
            JSONObject jsonObject = getOpenIdJson((String) temp.get("code"));
            logger.info("微信回复信息：" + jsonObject.toJSONString());
            String openId = jsonObject.get("openid").toString();

            QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("wxopenid", openId);
            member = this.getOne(wrapper);
            logger.info("判断是否存在，openid=" + openId);
            String sessionKey = (String) jsonObject.get("session_key");
            JSONObject userInfo = getWxInfo((String) temp.get("encryptedData"), sessionKey, (String) temp.get("iv"));
            logger.info(userInfo.toJSONString());
            String nickname = userInfo.getString("nickName");
            String nickname64 = com.qiniu.util.Base64.encodeToString(nickname.getBytes("utf-8"), com.qiniu.util.Base64.NO_WRAP);
            if (member != null) {
                logger.info("存在该用户，修改最后登录信息。");
                member.setNickname(nickname);
                member.setNickname64(nickname64);
                member.setUserImg(userInfo.getString("avatarUrl"));
                member.setWxopenid(openId);
                member.setPhone((String)temp.get("phone"));
                member.setGender(Integer.valueOf((String)temp.get("gender")));
                member.setBirthday((String)temp.get("birthday"));
                member.setLoginCount(member.getLoginCount() + 1);
                this.updateById(member);
            } else {
                logger.info("不存在该用户，新增。");
                member = new MemberEntity();

                member.setId(snowflakeIdWorker.nextId());
                member.setNickname(nickname);
                member.setNickname64(nickname64);
                member.setUserImg(userInfo.getString("avatarUrl"));
                member.setWxopenid(openId);
                member.setStatus(1);
                member.setParentName((String)temp.get("name"));
                member.setBirthday((String)temp.get("birthday"));
                member.setPhone((String)temp.get("phone"));
                member.setGender(Integer.valueOf((String)temp.get("gender")));
                member.setCreateTime(new Date());
                member.setLoginCount(0);
                String inviterIdStr = (String) temp.get("inviterId");
                if(StringUtils.isNotBlank(inviterIdStr)){
                    member.setInviterId(Long.parseLong(inviterIdStr));
                }
                this.save(member);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return member;
    }


    private JSONObject getOpenIdJson(String code) {
        Map params = new HashMap(4);
        params.put("secret", "7e205ae4c22785b0a551fbf843694285");
        params.put("appid", "wx19129ddbc418b8aa");
        params.put("grant_type", "authorization_code");
        params.put("js_code", code);
        logger.info("请求微信openid，参数:" + params.toString());
        String result = HttpGetUtil.httpRequestToString("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        logger.info("微信回复信息：" + jsonObject.toJSONString());
        return jsonObject;
    }

    private static JSONObject getWxInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSON.parseObject(result);
            }
        } catch (Exception e) {
        }
        return null;
    }
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
}
